package com.nervenets.web.controller.handler.user.user;

import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.hibernate.domain.user.User;

import javax.servlet.http.HttpServletRequest;

public class UserSetPwdHandler extends Handler<UserSetPwdParams> {
    @Override
    public String handle(UserSetPwdParams params, HttpServletRequest request) throws Exception {
        User user = userDao.findById(params.getUserId(), User.class);
        if (null == user) return errorMessage(MessageCode.code_777);

        if (!params.getOldPassword().equals(user.getPassword())) {
            return errorMessage(MessageCode.code_444, "旧密码不正确");
        }

        if (!(params.getPassword().length() >= 6 && params.getPassword().length() <= 20)) {
            return errorMessage(MessageCode.code_444, "请输入6-20位密码");
        }

        if (!params.getPassword().equals(params.getPasswordTry())) {
            return errorMessage(MessageCode.code_444, "两次输入的密码不一致！");
        }

        user.setPassword(params.getPassword());
        userDao.saveOrUpdate(user);
        globalService.clearRedisUserStored(user.getId());

        return successMessage(user);
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
